package com.happly.happlycloud.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.happly.happlycloud.common.Const;
import com.happly.happlycloud.common.ResponseCode;
import com.happly.happlycloud.common.ServerResponse;
import com.happly.happlycloud.dao.StateMapper;
import com.happly.happlycloud.dao.TutorInfoMapper;
import com.happly.happlycloud.dao.UserMapper;
import com.happly.happlycloud.pojo.State;
import com.happly.happlycloud.pojo.TutorInfo;
import com.happly.happlycloud.pojo.User;
import com.happly.happlycloud.service.IUserService;
import com.happly.happlycloud.util.DateTimeUtil;
import com.happly.happlycloud.util.MD5Util;
import com.happly.happlycloud.util.RedisPoolUtil;
import com.happly.happlycloud.vo.UserDetailVo;
import com.happly.happlycloud.vo.UserListVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.UUID;


@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StateMapper stateMapper;
    @Autowired
    private TutorInfoMapper tutorInfoMapper;
    @Autowired
    private MD5Util md5Util;

    @Override
    public ServerResponse<User> login(String username, String password) {
        int resultCount = userMapper.checkUsername(username);
        if(resultCount == 0 ){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }

        String md5Password = md5Util.MD5EncodeUtf8(password);
        User user  = userMapper.selectLogin(username,md5Password);
        if(user == null){
            return ServerResponse.createByErrorMessage("密码错误");
        }

        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登录成功",user);
    }



    public ServerResponse<String> register(User user){
        ServerResponse validResponse = this.checkValid(user.getUsername(),Const.USERNAME);
        if(!validResponse.isSuccess()){
            return validResponse;
        }
        validResponse = this.checkValid(user.getEmail(),Const.EMAIL);
        if(!validResponse.isSuccess()){
            return validResponse;
        }
        user.setRole(Const.Role.ROLE_CUSTOMER);
        //MD5加密
        user.setPassword(md5Util.MD5EncodeUtf8(user.getPassword()));
        int resultCount = userMapper.insert(user);
        if(resultCount == 0){
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccessMessage("注册成功");
    }

    public ServerResponse<String> checkValid(String str,String type){
        if(StringUtils.isNotBlank(type)){
            //开始校验
            if(Const.USERNAME.equals(type)){
                int resultCount = userMapper.checkUsername(str);
                if(resultCount > 0 ){
                    return ServerResponse.createByErrorMessage("用户名已存在");
                }
            }
            if(Const.EMAIL.equals(type)){
                int resultCount = userMapper.checkEmail(str);
                if(resultCount > 0 ){
                    return ServerResponse.createByErrorMessage("email已存在");
                }
            }
        }else{
            return ServerResponse.createByErrorMessage("参数错误");
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

    public ServerResponse selectQuestion(String username){

        ServerResponse validResponse = this.checkValid(username,Const.USERNAME);
        if(validResponse.isSuccess()){
            //用户不存在
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String question = userMapper.selectQuestionByUsername(username);
        if(StringUtils.isNotBlank(question)){
            return ServerResponse.createBySuccess(question);
        }
        return ServerResponse.createByErrorMessage("找回密码的问题是空的");
    }

    public ServerResponse<String> checkAnswer(String username,String question,String answer){
        int resultCount = userMapper.checkAnswer(username,question,answer);
        if(resultCount>0){
            //说明问题及问题答案是这个用户的,并且是正确的
            String forgetToken = UUID.randomUUID().toString();
            RedisPoolUtil.setEx(Const.TOKEN_PREFIX+username,forgetToken,60*60*12);
            return ServerResponse.createBySuccess(forgetToken);
        }
        return ServerResponse.createByErrorMessage("问题的答案错误");
    }



    public ServerResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken){
        if(StringUtils.isBlank(forgetToken)){
            return ServerResponse.createByErrorMessage("参数错误,token需要传递");
        }
        ServerResponse validResponse = this.checkValid(username,Const.USERNAME);
        if(validResponse.isSuccess()){
            //用户不存在
            return ServerResponse.createByErrorMessage("用户不存在");
        }

        String token = RedisPoolUtil.get(Const.TOKEN_PREFIX+username);
        if(StringUtils.isBlank(token)){
            return ServerResponse.createByErrorMessage("token无效或者过期");
        }

        if(StringUtils.equals(forgetToken,token)){
            String md5Password  = md5Util.MD5EncodeUtf8(passwordNew);
            int rowCount = userMapper.updatePasswordByUsername(username,md5Password);

            if(rowCount > 0){
                return ServerResponse.createBySuccessMessage("修改密码成功");
            }
        }else{
            return ServerResponse.createByErrorMessage("token错误,请重新获取重置密码的token");
        }
        return ServerResponse.createByErrorMessage("修改密码失败");
    }


    public ServerResponse<String> resetPassword(String passwordOld,String passwordNew,User user){
        //防止横向越权,要校验一下这个用户的旧密码,一定要指定是这个用户.因为我们会查询一个count(1),如果不指定id,那么结果就是true啦count>0;
        int resultCount = userMapper.checkPassword(md5Util.MD5EncodeUtf8(passwordOld),user.getId());
        if(resultCount == 0){
            return ServerResponse.createByErrorMessage("旧密码错误");
        }

        user.setPassword(md5Util.MD5EncodeUtf8(passwordNew));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMessage("密码更新成功");
        }
        return ServerResponse.createByErrorMessage("密码更新失败");
    }


    public ServerResponse<User> updateInformation(User user){
        //username是不能被更新的
        //email也要进行一个校验,校验新的email是不是已经存在,并且存在的email如果相同的话,不能是我们当前的这个用户的.
        int resultCount = userMapper.checkEmailByUserId(user.getEmail(),user.getId());
        if(resultCount > 0){
            return ServerResponse.createByErrorMessage("email已存在,请更换email再尝试更新");
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());

        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if(updateCount > 0){
            return ServerResponse.createBySuccess("更新个人信息成功",updateUser);
        }
        return ServerResponse.createByErrorMessage("更新个人信息失败");
    }

    public ServerResponse<User> getInformation(Integer userId){
        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null){
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);

    }

    public ServerResponse<Map> getStateInformation(Integer userId){
        User  user = userMapper.selectByPrimaryKey(userId);
        TutorInfo tutorInfo = tutorInfoMapper.selectByUserId(userId);
        Map map = Maps.newHashMap();

        List<State> state = stateMapper.findState();
        List<State> edstate = stateMapper.findEdState();
        if(tutorInfo == null){
            TutorInfo tutorInfo1 = new TutorInfo();
            tutorInfo1.setStatus(Const.ApplyStatusEnum.STATUS_noApply.getCode());
            map.put("tutorInfo",tutorInfo1);
            map.put("user",user);
            map.put("state",state);
            map.put("edstate",edstate);
            if(user == null){
                return ServerResponse.createByErrorMessage("找不到当前用户");
            }
            user.setPassword(StringUtils.EMPTY);
            return ServerResponse.createBySuccess(map);
        }
        map.put("tutorInfo",tutorInfo);
        map.put("user",user);
        map.put("state",state);
        map.put("edstate",edstate);
        if(user == null){
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(map);

    }

    //backend
    /**
     * 校验是否是管理员
     * @param user
     * @return
     */
    public ServerResponse checkAdminRole(User user){
        if(user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }

    @Override
    public ServerResponse checkToturRole(User user) {
        if(user != null && user.getRole().intValue() == Const.Role.ROLE_Totul){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }

    public ServerResponse<PageInfo> searchUser(String userName, Integer userId, String email, String phone, int pageNum, int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        if(StringUtils.isNotBlank(userName)){
            userName = new StringBuilder().append("%").append(userName).append("%").toString();
        }
        if(StringUtils.isNotBlank(email)){
            email = new StringBuilder().append("%").append(email).append("%").toString();
        }
        if(StringUtils.isNotBlank(phone)){
            phone = new StringBuilder().append("%").append(phone).append("%").toString();
        }
        List<User> userList = userMapper.selectByNameAndUserId(userName,userId,email,phone);
        List<UserListVo> userListVoList = Lists.newArrayList();
        for(User userItem : userList){
            UserListVo userListVo = assembleUserListVo(userItem);
            userListVoList.add(userListVo);
        }
        PageInfo pageResult = new PageInfo(userList);
        pageResult.setList(userListVoList);
        return ServerResponse.createBySuccess(pageResult);
    }


    public ServerResponse<PageInfo> getUserList(int pageNum,int pageSize){
        //startPage--start
        //填充自己的sql查询逻辑
        //pageHelper-收尾
        PageHelper.startPage(pageNum,pageSize);
        List<User> userList = userMapper.selectList();

        List<UserListVo> userListVoList = Lists.newArrayList();
        for(User userItem : userList){
            UserListVo userListVo = assembleUserListVo(userItem);
            userListVoList.add(userListVo);
        }
        PageInfo pageResult = new PageInfo(userList);
        pageResult.setList(userListVoList);
        return ServerResponse.createBySuccess(pageResult);
    }

    @Override
    public ServerResponse<Integer> setUserRole(Integer userId, Integer role, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        int result = userMapper.ChangeSetRole(userId,role);
        if (result>0){
            return  ServerResponse.createBySuccessMessage("更新用户权限成功");
        }
        return ServerResponse.createByErrorMessage("更新用户权限失败");
    }

    @Override
    public ServerResponse<UserDetailVo> manageUserDetail(Integer userId) {
        if(userId == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null){
            return ServerResponse.createByErrorMessage("用户可能已删除");
        }
        UserDetailVo userDetailVo = assembleUserDetailVo(user);
        return ServerResponse.createBySuccess(userDetailVo);
    }

    @Override
    public ServerResponse frose(Integer userId,int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        int result = userMapper.froseSetRole(userId);
        if (result>0){
            return  ServerResponse.createBySuccessMessage("更新用户权限成功");
        }
        return ServerResponse.createByErrorMessage("更新用户权限失败");
    }

    @Override
    public ServerResponse unfrose(Integer userId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        int result = userMapper.unfroseSetRole(userId);
        if (result>0){
            return  ServerResponse.createBySuccessMessage("更新用户权限成功");
        }
        return ServerResponse.createByErrorMessage("更新用户权限失败");
    }

    @Override
    public ServerResponse saveOrUpdateUser(User userMessage) {
        if(userMessage != null)
        {
            if(userMessage.getId() != null){
                int rowCount = userMapper.updateByPrimaryKey(userMessage);
                if(rowCount > 0){
                    return ServerResponse.createBySuccess("更新用户信息成功");
                }
                return ServerResponse.createBySuccess("更新用户信息失败");
            }else{
                int rowCount = userMapper.insert(userMessage);
                if(rowCount > 0){
                    return ServerResponse.createBySuccess("新增用户成功");
                }
                return ServerResponse.createBySuccess("新增用户失败");
            }
        }
        return ServerResponse.createByErrorMessage("新增或更新用户信息不正确");
    }

    public ServerResponse getAllCount() {

        Integer userCount = userMapper.getUserCount();
        Integer productCount = userMapper.getProductCount();
        Integer orderCount = userMapper.getOrderCount();
        Integer messageCount = userMapper.getMessageCount();
        Map countMap = Maps.newHashMap();
        countMap.put("productNum",productCount);
        countMap.put("userNum",userCount);
        countMap.put("orderNum",orderCount);
        countMap.put("messageNum",messageCount);
        return ServerResponse.createBySuccess(countMap);
    }

    @Override
    public ServerResponse getTutorCount(Integer id) {
        Integer productCount = userMapper.getProductTutorCount(id);
        Integer orderCount = userMapper.getOrderTutorCount(id);
        Integer messageCount = userMapper.getMessageTutorCount(id);
        Map countMap = Maps.newHashMap();
        countMap.put("productNum",productCount);
        countMap.put("orderNum",orderCount);
        countMap.put("messageNum",messageCount);
        return ServerResponse.createBySuccess(countMap);
    }


    private UserDetailVo assembleUserDetailVo(User user){
        UserDetailVo userDetailVo = new UserDetailVo();
        userDetailVo.setId(user.getId());
        userDetailVo.setUserName(user.getUsername());
        userDetailVo.setPassWord(user.getPassword());
        userDetailVo.setRole(user.getRole());
        userDetailVo.setEmail(user.getEmail());
        userDetailVo.setPhone(user.getPhone());
        userDetailVo.setQuestion(user.getQuestion());
        userDetailVo.setAnswer(user.getAnswer());
        userDetailVo.setCreateTime(DateTimeUtil.dateToStr(user.getCreateTime()));
        userDetailVo.setUpdateTime(DateTimeUtil.dateToStr(user.getCreateTime()));

        return userDetailVo;
    }

    private UserListVo assembleUserListVo(User user){
        UserListVo userListVo = new UserListVo();
        userListVo.setId(user.getId());
        userListVo.setUserName(user.getUsername());
        userListVo.setEmail(user.getEmail());
        userListVo.setPhone(user.getPhone());
        userListVo.setQuestion(user.getQuestion());
        userListVo.setAnswer(user.getAnswer());
        userListVo.setRole(user.getRole());
        return userListVo;
    }

}
